import { TRPCError } from '@trpc/server';
import { AdminService } from '../services/adminService';
import { t } from './trpc';

/**
 * 认证中间件 - 要求用户已登录
 */
export const authMiddleware = t.middleware(async ({ ctx, next }) => {
  if (!ctx.user) {
    throw new TRPCError({
      code: 'UNAUTHORIZED',
      message: 'Authentication required',
    });
  }

  return next({
    ctx: {
      ...ctx,
      user: ctx.user, // 确保user存在
    },
  });
});

/**
 * 管理员中间件 - 要求用户为管理员或子管理员
 */
export const adminMiddleware = authMiddleware.unstable_pipe(async ({ ctx, next }) => {
  const isAdmin = await AdminService.checkAdminPermission(ctx.user.userId);
  
  if (!isAdmin) {
    throw new TRPCError({
      code: 'FORBIDDEN',
      message: 'Admin permission required',
    });
  }

  return next({
    ctx,
  });
});

/**
 * 超级管理员中间件 - 要求用户为超级管理员
 */
export const superAdminMiddleware = authMiddleware.unstable_pipe(async ({ ctx, next }) => {
  const isSuperAdmin = await AdminService.checkSuperAdminPermission(ctx.user.userId);
  
  if (!isSuperAdmin) {
    throw new TRPCError({
      code: 'FORBIDDEN',
      message: 'Super admin permission required',
    });
  }

  return next({
    ctx,
  });
});

// 创建受保护的过程
export const protectedProcedure = t.procedure.use(authMiddleware);
export const adminProcedure = t.procedure.use(adminMiddleware);
export const superAdminProcedure = t.procedure.use(superAdminMiddleware);
